import React, {useEffect, useState} from 'react';
import {Breadcrumb} from "antd";
import {SecurityMenu} from "../../type/entity/SecurityMenu";
import RequestHandler from "../../http/RequestHandler";
import LogFactory from "../../log/LogFactory";
import {BreadcrumbItemType} from "antd/es/breadcrumb/Breadcrumb";
import {Link} from "react-router-dom";

const log = LogFactory.getLogger("NavigateBreadcrumb");
const NavigateBreadcrumb = () => {
    // const pathSnippets = window.location.pathname.split('/').filter(i => i);
    const [items, setItems] = useState<BreadcrumbItemType[]>([]);
    const prePath = React.useRef<string>();

    const [menuList, setMenuList] = useState<SecurityMenu[]>([]);
    useEffect(() => {
        RequestHandler.get<SecurityMenu[]>("/manager/admin/menu/list").then(res => {
            //
            // log.debug("菜单列表", res.data);
            if (res.success){
                setMenuList(res.data);
            }
        });
    }, []);
    if (menuList.length > 0 && prePath.current !== window.location.pathname){
        prePath.current = window.location.pathname;
        // log.debug("当前导航菜单", pathSnippets);
        // log.debug("准备渲染面包屑", menuList);
        let navList: BreadcrumbItemType[] = menuList.filter(m => window.location.pathname.includes(m.path))
            .map(m => {
                return {
                    title: window.location.pathname === m.path ? m.label : <Link key={m.key} to={m.path}>{m.label}</Link>,
                    // href: m.path,
                    // path: m.path,
                    key: m.key,
                };
            });
        navList.unshift({key: "main-key-breadcrumb", title: "导航首页", href: "/nav"});
        setItems(navList);
        // log.debug("面包屑菜单", navList);
    }


    return (
        <Breadcrumb
            // itemRender={ (c, params, item, paths) => {
            //     console.log(c, params, item, paths);
            //     return <span>{c.title}</span>;
            // } }
            style={{ margin: '16px 0' }}
            items={items}
        />
    );
};

export default NavigateBreadcrumb;